﻿using MySSO.Core;
using MySSO.Core.Service;
using MySSOMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace MySSOMVC.Controllers
{

    public class UserController : ApiController
    {
        private readonly string tokensecret = System.Configuration.ConfigurationManager.AppSettings["tokensecret"];
        private readonly AdminUserService _adminUserService;

        public UserController()
        {
            _adminUserService = new AdminUserService();
        }

        [HttpPost]
        public IHttpActionResult Index(UserRequest request)
        {
            try
            {
                MemoryCacheManager cacheManager = new MemoryCacheManager();
                string id_token = cacheManager.Get<string>(request.token);
                IDictionary<string, object> payload = JWTHelper.Decode(id_token, tokensecret);
                UserSSoModel userSSoModel = new UserSSoModel();
                userSSoModel.token = payload["token"].ToString();
                userSSoModel.uid = payload["uid"].ToString();
                userSSoModel.username = payload["name"].ToString();

                //刷新token,token过期时间为5分钟
                string newid_token=IdtokenHelper.RefreshIdtoken(payload, AppConstants.TokenExpireTime, tokensecret);
                cacheManager.Set(request.token, newid_token,30);
                var user = _adminUserService.GetAdminUserEntityById(long.Parse(payload["uid"].ToString()));
                if (user != null && !user.Disable)
                {
                    return Ok(new ResultBase<UserSSoModel> { code = "0", msg = "验证成功", data = userSSoModel });
                }
                else
                {
                    return Ok(new ResultBase<UserSSoModel> { code = "-1", msg = "用户不存在或者被禁用", data = null });
                }

            }
            catch (Exception ex)
            {
                return Ok(new ResultBase<UserSSoModel> { code = "-1", msg = ex.Message, data = null });
            }

        }
    }
}
